import binascii
import os 
# following imports are required by PKI
import Crypto
import Crypto.Random
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
import hashlib

import datetime
class Student:
    Name = ''
    Credits = 20.0
    _private_key = ''
    _public_key = ''
    def __init__(self,stuName):
        PrivateFile = "%s_Private.pem" % (stuName)
        if os.path.exists(PrivateFile):
            #导入已有账户的私钥
            with open(PrivateFile, "rb") as f:
                privatePemStr = f.read()
                self._private_key = Crypto.PublicKey.RSA.importKey(privatePemStr)
        else:
            #创建新的账户
            random = Crypto.Random.new().read
            self._private_key = RSA.generate(1024, random)
            # 保存密钥
            with open(PrivateFile, "wb") as f:
                privatePemStr = self._private_key.exportKey()   # 导出私钥
                f.write(privatePemStr)
                f.close()

        publickFile = "%s_Public.pem" % (stuName)
        if os.path.exists(publickFile):
            #导入已有账户的公钥
            with open(publickFile, "rb") as f:
                publicPemStr = f.read()
                self._public_key = Crypto.PublicKey.RSA.importKey(publicPemStr)
        else:
            self._public_key = self._private_key.publickey()
            publicPemStr = self._public_key.exportKey()   # 导出公钥
            with open(publickFile, "wb") as f:
                f.write(publicPemStr)
        #计算出账户
        str1 = binascii.hexlify(self._public_key.exportKey(format='DER')).decode('ascii')
        str2 = hashlib.sha256(str1.encode('utf-8')).hexdigest()
        str3 = hashlib.sha256(str2.encode('utf-8')).hexdigest()        
        self.Name = str3
        print("Account is ready: %s" % (self.Name))

class Transaction:
    def __init__(self, sender, recipient, value):
        if sender.Credits>value:
           sender.Credits -= value
           recipient.Credits += value
           self.time = datetime.datetime.now()
           print('Transaction finished at %s' %(self.time))

StuA = Student('A')
StuB = Student('B')
tran = Transaction(StuA,StuB,10)

print('Student: %s has %f credits' % (StuA.Name,StuA.Credits))
print('Student: %s has %f credits' % (StuB.Name,StuB.Credits))